﻿using System;
using UnityEngine;
using UnityEngine.UI;
using VRStandardAssets.Utils;

public class VRReticleTriggerItem : MonoBehaviour {
	public float progressDuration = 2f; //进度条填充需要的总时间
	public Image imageProgressBar;      //进度条图片
    //可订阅的事件
    public event Action OnTrigger; //定义类的订阅事件变量，以便被类的使用者订阅事件
    public event Action OnOver;//凝视移入
    public event Action OnOut;//凝视移出
	private VRInteractiveItem interactiveItem;	//GearVRSDK的对象可交互脚本
    public  bool isTrigger;//是否触发（进度条填充完成）
    public float timer = 0;//计时器   

	// Use this for initialization
	void Awake () {
		//要保证对象也有VRInteractiveItem脚本，实例变量interactiveItem初始化
		interactiveItem = GetComponent<VRInteractiveItem> ()  ?? gameObject.AddComponent<VRInteractiveItem>(); 	
		if (imageProgressBar == null)//确保有进程条图片组件
            imageProgressBar = GameObject.Find("ring").GetComponent<Image>();
		imageProgressBar.fillAmount = 0f;	//初始为0
	}

    //对象使能（激活）时调用
    void OnEnable()
    {
        interactiveItem.OnOver += HandleOver;//订阅事件，可以根据需要增加订阅的事件
        interactiveItem.OnOut += HandleOut;
    }

    //对象不使能（不激活）时调用
    void OnDisable()
    {
        interactiveItem.OnOver -= HandleOver;//去掉订阅的事件
        interactiveItem.OnOut -= HandleOut;
	}

    // 每一帧调用    
	private void Update () {
		//准星凝视移入对象上面，且触发变量为false
        if (interactiveItem.IsOver && isTrigger == false)  
        {
            timer += Time.deltaTime;//累计当前帧时间
            if (timer < progressDuration)
            {  //计时变量的值转换为进度条的填充量值
                imageProgressBar.fillAmount = timer / progressDuration; 
            }
            else
            {   //进度条总计时间到了
                imageProgressBar.fillAmount = 1;
                isTrigger = true;
                timer = 0;
                if (OnTrigger != null)
                    OnTrigger();
            }
        }      
	}

    //准星凝视移入对象上时调用   
    private void HandleOver()
    {
        if (OnOver!=null)
            OnOver();
    }

    //准星凝视移出对象时调用
    private void HandleOut()
    {
        isTrigger = false;
        timer = 0;
        imageProgressBar.fillAmount = 0f;//进度条填充置0 
        if (OnOut!=null)
            OnOut();
	}
}


